const svg = d3.select('svg');

const width = +svg.attr('width');
const height = +svg.attr('height');

const render = data => {
  const xValue = d => d.population;
  const yValue = d => d.city;
  const margin = { top: 80, bottom: 30, left: 100, right: 20};
  const innerWidth = width - margin.left - margin.right;
  const innerHeight = height - margin.top - margin.bottom;
  
  const circleRadius = 10;
  
  const xScale = d3.scaleLinear()
    .domain([0, d3.max(data, xValue)])
	.range([0, innerWidth])
	.nice();
  
  const yScale = d3.scalePoint()
    .domain(data.map(yValue))
	.range([0, innerHeight])
	.padding(0.2);//轴间距
	
  
  const g = svg.append('g')
    .attr('transform',`translate(${margin.left},${margin.bottom})`);
  
  const yAxis = d3.axisLeft(yScale)
    .tickSize(-innerWidth);
  
  const yAxisGroup = g.append('g').call(yAxis);
  yAxisGroup.selectAll('.domain')
	.remove();
  yAxisGroup.append('text')
    .attr('fill', 'black')
    .attr('x', 0)
	.attr('y', -10);
	//.text('城市');
  
  //格式化x轴数据
  const xAxisFormat = number => number == 0 ? 0 : number/10000 + '万';
  const xAxis = d3.axisBottom(xScale)
    .tickFormat(xAxisFormat)
	//添加网格线
	.tickSize(-innerHeight);
 
  const xAxisGroup = g.append('g').call(xAxis)
    .attr('transform',`translate(0, ${innerHeight})`);
  //去除x轴轴线
  xAxisGroup.selectAll('.domain').remove();
  //添加x轴名称
  xAxisGroup.append('text')
    .attr('fill', 'black')
    .attr('y', 40)
	.attr('x', innerWidth/2);
	//.text('人口（万）');
  
  
  /*使用d3自带API的line()方法组成path的d属性  即 M x0,y0 L x1,y1 ..... Z*/
  const dataSet = d3.line()
    .x(d => xScale(d.population) + margin.left)
	.y(d => yScale(d.city) + margin.bottom);
	//.curve(d3.curveBasis);
	
  /* 不使用d3方法,自己写函数组成path的d属性
  const dataSet = data => {
	const results = '';
	let i = 0;
	data.forEach(d => {
	  let x = xScale(d.population) + margin.left;
	  let y = yScale(d.city) + margin.bottom;
	  let obj = {'x' : x, 'y' : y};
	  list.push(obj);
	  
	  let str = i == 0 ? `M${x},${y} ` : `L${x},${y} `;
	  results += str;
	  i++;
	})
	//console.log(results);
	return results;
  }*/
  
  //添加折线
  svg.append('g')
    .attr('class', 'lines')
	.append('path')
	.attr('d', dataSet(data))
	.attr('stroke', 'red') //颜色
	.attr('fill', 'none')
	.attr('stroke-width', '2');
  
  
  
  g.selectAll('circle').data(data)
    .enter().append('circle')
      .attr('cy', d => yScale(yValue(d)))
      .attr('cx', d => xScale(xValue(d)))
      .attr('r', circleRadius)
	  .append('title')
	  .text(function(d){
	    return `${d.city} : ${d.population/10000}万`
	  });
	  
  g.append('text')
    .attr('y', -10)
	.attr('x',innerWidth/3)
	.text('中国人口最多的十个省会城市');
}

d3.csv('data.csv').then( data => {
  data.forEach(d => {
	d.population = +d.population * 10000;  
  });
  render(data);
});